﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web.Http;
using ETWebApi2.Models;
using Model;

namespace ETWebApi2.Controllers
{
    [Route("companyfile"), JwtAuthActionFilter]
    public class CompanyFileController : ApiController
    {      
        private MyETLockContext m_db = new MyETLockContext();
        /// <summary>
        /// 加载初始数据以及条件查询 
        /// </summary>
        /// <param name="QuerySTime"></param>
        /// <param name="QueryETime"></param>
        /// <param name="QueryKey"></param>
        /// <param name="QueryType">  2是上传，1是已下载， 0是未下载</param>
        /// <returns></returns>
        [HttpGet]
        public HttpResponseMessage GetFiles(string query, int QueryType, int page, int limit, DateTime? STime = null, DateTime? ETime = null)
        {
            JwtAuthObject cuser = new BaseClass().GetInfoByToken(Request.Headers.Authorization.Parameter);
            //CUser_tb cuser = new BaseClass().GetUserById(35);
            int type = Convert.ToInt32(QueryType); //2是上传，1是已下载， 0是未下载
            if (ETime == null)
                ETime = DateTime.Now;
            if (STime == null)
                STime = Convert.ToDateTime("2000-01-01") ;
            
            string TimeRange = string.Format("and {0} >='{1}' and {0} <='{2}'", "Files_tb.Time", STime,ETime);
            List<Files_tb> fList = new List<Files_tb>();
            if (type == 2)//上传记录
            {               
                if (!string.IsNullOrEmpty(query))
                {   //对上传的文件名、接收方公司名的搜索有效
                    string sql = string.Format("select * from Files_tb inner join CUser_tb on Files_tb.UploadUserId=CUser_tb.Id where CUser_tb.CompanyId={0} and (Files_tb.Attachment like '%{1}%' or Files_tb.CompanyId in(select Id from Customers_tb where Customers_tb.Name like '%{1}%'))  {2} order by Files_tb.Time desc", cuser.CurentCopmpanyId, query, TimeRange);//or Files_tb.Attachment like '%{2}%' 
                    using (var m_db = new MyETLockContext())
                    {
                        fList = m_db.Database.SqlQuery<Files_tb>(sql).ToList();
                    }
                }
                else//没有输入关键词 
                {
                    string sql = string.Format("select * from Files_tb inner join CUser_tb on Files_tb.UploadUserId=CUser_tb.Id where CUser_tb.CompanyId={0}  {1} order by Files_tb.Time desc", cuser.CurentCopmpanyId, TimeRange);//or Files_tb.Attachment like '%{2}%' 
                    using (var m_db = new MyETLockContext())
                    {
                        fList = m_db.Database.SqlQuery<Files_tb>(sql).ToList();
                    }
                }
            }
            else  //下载记录
            {
                string downType = "<>0";
                if (type == 0)  //2是上传，1是已下载， 0是未下载  and Files_tb.IsValid=1
                    downType = "=0 ";

                string sqls = "";
                if (!string.IsNullOrEmpty(query))
                {
                    //下载记录的搜索对 文件名、下载人名有效（暂不支持发送方的公司名搜索）
                    sqls = string.Format("and (Files_tb.Attachment like '%{0}%' or (select count(*) from CUser_tb where CUser_tb.UserName like '%{0}%' and CUser_tb.Id = Files_tb.dUserId) > 0)", query);//or Files_tb.Attachment like '%{2}%' 
                }
                string sql = string.Format("select * from Files_tb where CompanyId={0} and dUserId{1} {2} {3} order by dTime desc", cuser.CurentCopmpanyId, downType, TimeRange, sqls);
                using (var m_db = new MyETLockContext())
                {
                    fList = m_db.Database.SqlQuery<Files_tb>(sql).ToList();
                }
            }
            int startRow = (page - 1) * limit;
            if (fList.Count > 0)
            {
                List<FilesShow> showDatas = ShowData(fList.Skip(startRow).Take(limit).ToList(), Convert.ToInt32(QueryType));
                return ObjectToJson.toJson(new { status = 200, data = new { total = fList.Count, rows = showDatas } });
            }
            else
                return ObjectToJson.toJson(new { status = 200, data = new { total = 0, rows = 0 } });
        }


        private List<FilesShow> ShowData(List<Files_tb> datas, int type)
        {
            List<FilesShow> files = new List<FilesShow>();
            BaseClass bc = new BaseClass();
            for (int i = 0; i < datas.Count; i++)
            {
                FilesShow file = new FilesShow();
                file.Id = datas[i].Id;
                file.FileName = datas[i].Attachment;
                if (type == 2) //找接收方
                {
                    file.Name = bc.GetCompanyName((int)datas[i].CompanyId);
                    file.UserName = bc.GetUserNameByUid((int)datas[i].UploadUserId);
                }
                else
                {
                    file.Name = bc.GetCompanyName(bc.GetCompanyIdByUid((int)datas[i].UploadUserId));
                    if (type == 0)
                        file.UserName = bc.GetUserNameByUid((int)datas[i].UploadUserId);
                    else
                        file.UserName = bc.GetUserNameByUid(datas[i].dUserId);
                }
                file.IP = datas[i].dIP;
                file.Time = Convert.ToDateTime(datas[i].Time).ToString("yyyy-MM-dd");
                file.DownloadTime = Convert.ToDateTime(datas[i].dTime).ToString("yyyy-MM-dd");
                files.Add(file);
            }
            return files;
        }
        

    }
}
